import React, { Component } from 'react'
import classnames from 'classnames'
export default class TodoItem extends Component {
  state = {
    currentId: '',
    currentName: ''
  }
  inputRef = React.createRef()
  render() {
    const { item } = this.props
    return (
      <div>
        <li
          key={item.id}
          // item.done ? 'completed' : '', item.id === this.state.currentId ? 'editing' : ''
          className={classnames({
            completed: item.done,
            editing: item.id === this.state.currentId
          })}>
          <div className="view">
            <input
              className="toggle"
              onChange={() => this.updateDone(item.id)}
              type="checkbox"
              checked={item.done} />
            <label onDoubleClick={() => this.showEdit(item)}>{item.name}</label>
            <button onClick={() => this.delTodo(item.id)} className="destroy"></button>
          </div>
          <input
            onBlur={() => this.setState({ currentId: '' })}
            ref={this.inputRef}
            onKeyUp={this.handleKeyup}
            onChange={(e) => { this.setState({ currentName: e.target.value }) }}
            className="edit" value={this.state.currentName} />
        </li>
      </div>
    )
  }
  delTodo = (id) => {
    // console.log(id);
    this.props.delTodoById(id)
  }
  updateDone = (id) => {
    this.props.updateDone(id)
  }
  showEdit = ({ id, name }) => {
    this.setState({
      currentId: id,
      currentName: name
    },
      () => {
        this.inputRef.current.focus()
      })//第二个回调函数：等dom更新完后执行
  }
  handleKeyup = e => {
    if (e.keyCode === 27) {
      this.setState({
        currentId: '',
        currentName: ''
      })
    }
    if (e.keyCode === 13) {
      this.props.editTodo(this.state.currentId, this.state.currentName)
      // console.log(this.state.currentName);
      this.setState({
        currentId: '',
        currentName: ''
      })
    }
  }
  // componentDidUpdate() {
  //   this.inputRef.current.focus()
  // }
}
